﻿using UnityEngine;
using System.Collections;

public class MapExplorer : MonoBehaviour {
    public Stats stats;
    MapGenerator map;
    LevelManager level;
    void Start(){
        stats = gameObject.GetComponent<Stats>();
        map = GameObject.FindGameObjectWithTag("GameManager").GetComponent<MapGenerator>();
        level = GameObject.FindGameObjectWithTag("GameManager").GetComponent<LevelManager>();
		RefreshAllVisuals();
    }
    public void RefreshAllVisuals() {
        ExploreMap();
		EnemyUpdateVisual();
    }
    public void ExploreMap() {
        int aux = 2;
        int minx = (int)(transform.position.x - stats.ViewDistance) - aux< 0 ? 0 : (int)(transform.position.x - stats.ViewDistance) - aux;
        int maxx = (int)(transform.position.x + stats.ViewDistance) + aux > level.mapa.theMap.Tiles.GetLength(0) ? level.mapa.theMap.Tiles.GetLength(0) : (int)(transform.position.x + stats.ViewDistance) + aux;
        int miny = (int)(transform.position.z - stats.ViewDistance) - aux < 0 ? 0 : (int)(transform.position.z - stats.ViewDistance) - aux;
        int maxy = (int)(transform.position.z + stats.ViewDistance) + aux > level.mapa.theMap.Tiles.GetLength(1) ? level.mapa.theMap.Tiles.GetLength(1) : (int)(transform.position.z + stats.ViewDistance) + aux;
        for (int i = minx; i < maxx; i++)
        {
            for (int j = miny; j < maxy; j++)
            {
                if (map.theMap.Tiles[i, j])
                {
                    GameObject go = map.theMap.Tiles[i, j];
                    Renderer ren = go.GetComponentInChildren<Renderer>();
                    if (Vector3.Distance(go.transform.position, transform.position) <= stats.ViewDistance)
                    {
                        ren.enabled = true;
                        ren.material.color = Color.white;
                    }
                    else {
                        ren.material.color = Color.gray;
                    }
                }
            }
        }
        
    }
    public void EnemyUpdateVisual()
    {
        foreach (var item in level.EnemysTurn)
        {
            if (!item) return;
            if (Vector3.Distance(item.transform.position, transform.position) <= stats.ViewDistance)
            {
                item.GetComponentInChildren<SpriteRenderer>().enabled = true;
            }
            else
            {
                item.GetComponentInChildren<SpriteRenderer>().enabled = false;
            }
        }
    }
}
